package com.cimu.umeng;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.net.HttpResponse;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

@Slf4j
public class PushClient {

	// The user agent
	protected final String USER_AGENT = "Mozilla/5.0";

	// This object is used for sending the post request to Umeng
    private static OkHttpClient client;

    private static OkHttpClient getClient() {
        if (client == null) {
            client = new OkHttpClient.Builder().addInterceptor(new HttpLogInterceptor())
                    .connectTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .build();
        }
        return client;
    }
	// The host
	protected static final String host = "http://msg.umeng.com";

	// The upload path
	protected static final String uploadPath = "/upload";

	// The post path
	protected static final String postPath = "/api/send";

	public ApiResult send(UmengNotification msg) throws Exception {
		String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
		msg.setPredefinedKeyValue("timestamp", timestamp);
        String url = host + postPath;
        String postBody = msg.getPostBody();
        String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
        url = url + "?sign=" + sign;

        MediaType mediaTypeJSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaTypeJSON,postBody);

        Request.Builder builder = new Request.Builder()
                .addHeader("User-Agent", USER_AGENT)
                .url(url).post(requestBody);
        //采用post的方式进行提交
        Request request = builder.build();
        try (Response response = getClient().newCall(request).execute()) {
            String result = response.body().string();
            log.info("【友盟推送】发送请求返回值:[{}]",result);
            return JSON.toJavaObject(JSON.parseObject(result), ApiResult.class);
        } catch (IOException e) {
            ApiResult apiResult = new ApiResult();
            apiResult.setRet("FAIL");
            ApiResultData apiResultData = new ApiResultData();
            apiResultData.setErrorMsg(e.getMessage());
            apiResult.setData(apiResultData);
            return apiResult;
        }
    }

	// Upload file with device_tokens to Umeng
	public ApiResult uploadContents(String appkey,String appMasterSecret,String contents) throws Exception {
		// Construct the json string
		JSONObject uploadJson = new JSONObject();
		uploadJson.put("appkey", appkey);
		String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
		uploadJson.put("timestamp", timestamp);
		uploadJson.put("content", contents);
		// Construct the request
		String url = host + uploadPath;
		String postBody = uploadJson.toString();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
		url = url + "?sign=" + sign;

        MediaType mediaTypeJSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaTypeJSON,postBody);

        Request.Builder builder = new Request.Builder()
                .addHeader("User-Agent", USER_AGENT)
                .url(url).post(requestBody);
        //采用post的方式进行提交
        Request request = builder.build();
        try (Response response = getClient().newCall(request).execute()) {
            String result = response.body().string();
            log.info("【友盟推送】发送请求返回值:[{}]",result);
            return JSON.toJavaObject(JSON.parseObject(result), ApiResult.class);
        } catch (IOException e) {
            ApiResult apiResult = new ApiResult();
            apiResult.setRet("FAIL");
            ApiResultData apiResultData = new ApiResultData();
            apiResultData.setErrorMsg(e.getMessage());
            apiResult.setData(apiResultData);
            return apiResult;
        }
	}

}
